# -*- coding: utf-8 -*-
import scrapy
from  scrapy import Request,FormRequest
import json
from scrapy.log import logger
from PIL import Image
from io import BytesIO
from scrapy.linkextractors import LinkExtractor
class LoginSpider(scrapy.Spider):
    name = 'login'

    start_urls = ['http://jw1.wucc.cn/xs_main.aspx?xh=16210506042']

    def parse(self, response):
        title=response.xpath('//title/text()').extract_first()
        #//*[@id="xh"]
        le=LinkExtractor(restrict_xpaths='//*[@id="headDiv"]/ul/li[7]/ul/li[1]/a')
        for link in le.extract_links(response):
            print(link.url)
            yield Request(link.url,callback=self.info)
        print(title)
    def info(self,response):
        second=response.xpath('//title/text()').extract_first()
        xuehao=response.xpath('//*[@id="xh"]/text()').extract_first()
        name = response.xpath('//*[@id="xm"]/text()').extract_first()
        xy = response.xpath('//*[@id="xy"]/text()').extract_first()
        zy = response.xpath('//*[@id="zy"]/text()').extract_first()
        print(xuehao)
        print(name)
        print(xy)
        print(zy)
    login_url='http://jw1.wucc.cn/'
    txtUserName='16210506042'
    TextBox2='123456zjd'
    def start_requests(self):
        yield Request(self.login_url,callback=self.login,dont_filter=True)
    def login(self,response):
        login_response=response.meta.get('login_response')
        if not login_response:
            captchaURL=response.xpath('//dl[@style="POSITION:relative"]/dd/img/@src').extract_first()
            captchaURL=response.urljoin(captchaURL)
            print('获取验证码----')
            yield Request(captchaURL,callback=self.login,meta={'login_response':response},dont_filter=True)
        else:
            formdata={
                'txtUserName':self.txtUserName,
                'TextBox2':self.TextBox2,
                'txtSecretCode':self.get_captcha_by_user(response.body)
            }
            print('战神皮皮迪要提交表单了哦')
            yield FormRequest.from_response(login_response,callback=self.parse,formdata=formdata,dont_filter=True)

    # def get_captcha_by_OCR(self,data):
    #     img=Image.open(BytesIO(data))
    #     img=img.convert('L')
    #     captcha=pytesseract.image_to_string(img)
    #     img.close()
    #     return captcha
    def get_captcha_by_user(self,data):
        img=Image.open(BytesIO(data))
        img.show()
        captcha=input("输入验证码:")

        return captcha